﻿using System;
using System.Collections.Generic;
using AccessControl.Wpf.ViewModels;
using AccessControl.Contracts.Models;
using System.Collections.ObjectModel;
using System.Windows.Input;
using AccessControl.Wpf.Commands;
using AccessControl.Gateway.Managers;

namespace AccessControl.Wpf.Entries.ViewModels
{
	class EntryViewModel : ViewModel, ICloseableViewModel
	{
		#region Fields

		IEntry _Entry;
		ObservableCollection<CameraViewModel> _Cameras = new ObservableCollection<CameraViewModel>();

		#endregion

        #region Commands

        public ICommand OpenEntryCommand
        {
            get { return new CommandBaseOfT<IEntry>(OpenEntry); }
        }

        public ICommand CloseEntryCommand
        {
            get { return new CommandBaseOfT<IEntry>(CloseEntry); }
        }

        #endregion

        #region Public Properties

        public IEntry Entry
		{
			get { return _Entry; }
			set
			{
				if (_Entry != value)
				{
					_Entry = value;
					NotifyPropertyChanged("Entry");
				}
			}
		}

		public IList<CameraViewModel> Cameras
		{
			get { return _Cameras; }
		}

		#endregion

		#region ICloseableViewModel Members

		public void Close()
		{
			foreach (CameraViewModel cameraViewModel in Cameras)
				cameraViewModel.StopVideo();
		}

		#endregion

        #region Private Members

        private void OpenEntry(IEntry entry)
        {
            ChangeEntryState(entry, EntryState.Opened);
        }

        private void CloseEntry(IEntry entry)
        {
            ChangeEntryState(entry, EntryState.Closed);
        }

        private void ChangeEntryState(IEntry entry, EntryState state)
        {
            foreach (IEntry e in Session.Instance.EntriesManager.Items)
            {
                if (e.Id == entry.Id)
                {
                    e.State = state;
                    break;
                }
            }

            foreach (IMap map in Session.Instance.MapsManager.Items)
            {
                foreach (IMapEntry e in map.Entries)
                {
                    if (e.Id == entry.Id)
                    {
                        e.State = state;
                        break;
                    }
                }
            }
        }

        

        #endregion
    }
}
